/*
 * @Author: 杰编程 2306248989@qq.com
 * @Date: 2023-08-06 13:28:42
 * @LastEditors: 杰编程 2306248989@qq.com
 * @LastEditTime: 2023-08-07 15:24:01
 * @FilePath: /lesson25/tcp/log.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once

#include <string>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <unistd.h>

enum
{
    Debug = 0,
    Info,
    Warning,
    Error,
    Fatal,
    Uknown
};

const std::string filename = "log/log.txt"; // 将日志统一打印到log目录里面

std::string getLevel(int level)
{
    switch (level)
    {
    case Debug:
        return "Debug";
    case Info:
        return "Info";
    case Warning:
        return "Warning";
    case Error:
        return "Error";
    case Fatal:
        return "Fatal";
    default:
        return "Uknown";
    }
}

std::string getCurTime()
{
    time_t cur_time = time(nullptr);
    struct tm *now = localtime(&cur_time);
    char buffer[128];
    snprintf(buffer, sizeof(buffer), "%d-%d-%d %d:%d:%d", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday,
             now->tm_hour, now->tm_sec, now->tm_sec);
    return buffer;
}

// 日志格式: 日志等级 时间 pid   消息体
// logMessage(DEBUG, "hello: %d, %s", 12, s.c_str()); // DEBUG hello:12, world
void logMessage(int level, const char *format, ...)
{
    char bufferLeft[1024];
    std::string loglevel = getLevel(level);
    std::string cur_time = getCurTime();
    snprintf(bufferLeft, sizeof(bufferLeft), "[%s] [%s] %d:", loglevel.c_str(), cur_time.c_str(), getpid());

    char bufferRight[1024];
    va_list p;
    va_start(p, format);
    vsnprintf(bufferRight, sizeof(bufferRight), format, p);
    va_end(p);

    printf("%s%s\n", bufferLeft, bufferRight);

    // 日志信息持久化
    // FILE *fp=fopen(filename.c_str(),"a");
    // if(fp==nullptr)return;
    // fprintf(fp,"%s%s\n",bufferLeft,bufferRight);
    // fflush(fp);//可写可不写
    // fclose(fp);
}
